#!/usr/bin/env bash

# sc-install.sh
#
# Purpose: Install AC2's System Controller 
# Usage: see usage()
# Description: 
#
#
#OSX_HTDOCS=~/Sites
XAMPP_HTDOCS=/Applications/xampp/xamppfiles/htdocs
SYMS="public gfx css js" # symlinks to create
SC_SOURCE=


AC2DIR=~/ac2  # system controller directory

# Command-line opts
VERBOSE=0


usage() {
cat << EOF
usage: $0 -d dirname  [ -v ]

This script installs the SystemController web application.

OPTIONS:
  -u      uninstall
  -d      Verbose

EOF
}


verbose() {
       [ $VERBOSE -eq 1 ] && $@ || :
}



init() {
    verbose echo  "+++ init: source directory=${DIR}, ac2 dir=${AC2DIR}"
    
    # check if source directory exists
    export SC_SOURCE=${DIR}/SystemController
    
    if [ ! -d "${SC_SOURCE}" ]; then
      echo "Directory ${SC_SOURCE} does not exist."
      exit 1
    fi    
    verbose echo  "+++ init: system controller source=${SC_SOURCE}"
    
    mkdir -pv $AC2DIR
}



getargs() {
    verbose echo  "+++ getargs: $@"
    local dir_fg=0
    while getopts "d:vu" OPTION; do
        case $OPTION in
            h)
                usage
                exit 1
                ;;
            u)
                verbose echo  "+++ getargs: uninstall"
                clean_up
                ;;
            d)
                VERBOSE=1
                verbose echo  "+++ getargs: verbose=1"
                ;;
            ?)
                usage
                exit
                ;;
        esac
    done
}

clean_up() {
    # Remove AC2DIR files
    if [ -d ${AC2DIR} ]; then
        verbose echo  "+++ clean_up: remove dir ${AC2DIR}" 
        rm -r ${AC2DIR}
    fi
    
    # Remove symlinks
    for src in $SYMS; do 
        dst=$src
        if [ $src == "public" ]; then 
            dst="ac2"
        fi
        echo $XAMPP_HTDOCS/$dst
        if [ -h $XAMPP_HTDOCS/$dst ]; then 
            verbose echo  "+++ clean_up: remove symlink $XAMPP_HTDOCS/$dst"        
            rm $XAMPP_HTDOCS/$dst
        fi
    done

    exit 0
}



main() {
    getargs $@
    init
    
    # copy SystemController files to AC
    verbose echo  "+++ main: copying ${SC_SOURCE} files to ${AC2DIR}..."
    #cp -r $SC_SOURCE $AC2DIR 2> /dev/null
        
    # change permissions on $AC2DIR
    verbose echo  "+++ main: setiing permissions on ${AC2DIR}..."
    #chmod -R 777 $AC2DIR
    
    # create symlinks
    verbose echo  "+++ main: creating symlinks..."
    for src in $SYMS; do 
        dst=$src
        if [ $src == "public" ]; then 
            dst="ac2"
        fi
        echo $XAMPP_HTDOCS/$dst
        if [ -h $XAMPP_HTDOCS/$dst ]; then 
            echo "$dst exists"
        fi
        #ln -s $AC2DIR/$src $XAMPP_HTDOCS/$dst
    done

    # create 
}


trap clean_up SIGHUP SIGINT SIGTERM

main $@
